// 自定义的一些js方法，需要再客户端运行
import { useInterstitialObserver } from "~/composables/useInterstitialObserver.client.js";

function getParam(name) {
  try {
    var searchParams = new URLSearchParams(window.location.search);
    if (searchParams.has(name)) {
      return searchParams.get(name).trim();
    } else {
      return "";
    }
  } catch (e) {
    return "";
  }
}

// posthog的事件上报
const PosthogEvent = (eventName, attrs = {}) => {
  if (typeof window !== "undefined" && window.posthog) {
    window.posthog.capture(eventName, attrs);
  }
};

// GA的事件上报
const GAEvent = (eventName, attrs = {}) => {
  if (typeof window !== "undefined") {
    const route = useRoute();
    const network = getParam("network");
    const channel = getParam("channel");
    if (channel) {
      console.log("GtagLogEvent", eventName, attrs);
    }
    let page = "";
    if (route.path === "/") {
      page = "Home";
    } else if (route.path.startsWith("/categories/")) {
      page = "Category";
    } else if (route.path.startsWith("/search/")) {
      page = "Search";
    } else if (route.path.startsWith("/video/")) {
      page = "Play";
    } else if (route.path.startsWith("/themes/")) {
      page = "ThemeDetail";
    } else if (route.path === "/themes") {
      page = "Theme";
    }
    let val = {
      Network: network,
      Channel: channel,
      Page: page,
    };
    Object.assign(val, attrs);

    if (window.gtag) {
      window.gtag("event", eventName, val);
    }
    PosthogEvent(eventName, val);
  }
};

// tiktok的事件上报
const TikTokEvent = (eventName, attrs = {}) => {
  if (typeof window !== "undefined") {
    if (!window.ttq) {
      console.log("tt init error");
      return;
    }
    if (eventName === "page_view") {
      console.log("tt: ", "page_view: pageView");
      window.ttq.page();
    } else if (eventName === "GAM_AD_Click_All") {
      // GAM自动插屏、GAM自动锚定、GAM手动页内/激励视频广告
      console.log("tt: ", "GAM_AD_Click_All: ClickButton");
      window.ttq.track("ClickButton", attrs);
    } else if (eventName === "GAM_Inter_Click_Auto") {
      // 点击GAM广告中的自动插屏广告
      console.log("tt: ", "GAM_Inter_Click_Auto: AddPaymentInfo");
      window.ttq.track("AddPaymentInfo", attrs);
    } else if (eventName === "GAM_Anc_Click_Auto") {
      // 点击GAM广告中的自动锚定点击
      console.log("tt: ", "GAM_Anc_Click_Auto: AddToWishlist");
      window.ttq.track("AddToWishlist", attrs);
    }
  }
};
// 事件上报总入口
export const trackEvent = (eventName, gaAttrs = {}, attrs = {}) => {
  let network = getParam("network");
  switch (network) {
    case "tiktok":
      TikTokEvent(eventName, attrs);
      break;
    default:
      break;
  }
  GAEvent(eventName, gaAttrs);
};

export const trackVideoClick = (subzone, title) => {
  trackEvent("Click_Video", {
    Subzone: subzone,
    Video: title,
  });
};

function getPositionNameAndPath(event, gamConfig) {
  // console.log(event.slot.getAdUnitPath())
  // const parts = event.slot.getAdUnitPath().split('/')
  // const path = parts.slice(2).join('/')
  // 获取广告位的位置，以便根据位置获取对应的afc广告代码
  let positionName;
  let path = event.slot.getAdUnitPath();
  if (gamConfig) {
    for (let k in gamConfig) {
      if (gamConfig[k] === path) {
        positionName = k;
      }
    }
  }
  return {
    positionName,
    path,
  };
}

// GAM自动广告展示回调
function gamAutoAdShowCallback(event, gamConfig) {
  // 解析实际广告名
  const { positionName, path } = getPositionNameAndPath(event, gamConfig);

  if (event.isEmpty) {
    // gam展示失败
    if (positionName === "topAnchorSlot") {
      trackEvent("GAM_Anc_AD_Show_Fail_Auto", { Adslot: path });
      trackEvent("GAM_AD_Show_Fail_Auto", { Adslot: path });
    } else if (positionName === "bottomAnchorSlot") {
      trackEvent("GAM_Anc_AD_Show_Fail_Auto", { Adslot: path });
      trackEvent("GAM_AD_Show_Fail_Auto", { Adslot: path });
    } else if (positionName === "interstitialSlot") {
      trackEvent("GAM_Inter_AD_Show_Fail_Auto", { Adslot: path });
      trackEvent("GAM_AD_Show_Fail_Auto", { Adslot: path });
    }
  } else {
    // gam展示成功
    if (positionName === "topAnchorSlot") {
      trackEvent("GAM_Anc_AD_Show_Auto", { Adslot: path });
      trackEvent("GAM_AD_Show_Auto", { Adslot: path });
    } else if (positionName === "bottomAnchorSlot") {
      trackEvent("GAM_Anc_AD_Show_Auto", { Adslot: path });
      trackEvent("GAM_AD_Show_Auto", { Adslot: path });
    } else if (positionName === "interstitialSlot") {
      nextTick(() => {
        useInterstitialObserver().setObserver();
      });
      trackEvent("GAM_Inter_AD_Show_Auto", { Adslot: path });
      trackEvent("GAM_AD_Show_Auto", { Adslot: path });
    }
  }
}

// GAM自动广告展示追踪
const gamAutoAdShowTrack = (gamConfig) => {
  if (typeof window !== "undefined") {
    if (gamConfig && !gamConfig.close) {
      window.googletag = window.googletag || { cmd: [] };
      googletag.cmd.push(function () {
        googletag.pubads().addEventListener("slotRenderEnded", (event) => {
          gamAutoAdShowCallback(event, gamConfig);
        });
      });
    }
  }
};

// GAM自动广告初始化
let topAnchorSlot, bottomAnchorSlot, interstitialSlot;
const GAMAutoAdInit = (gamConfig) => {
  if (typeof window !== "undefined") {
    if (gamConfig && !gamConfig.close) {
      window.googletag = window.googletag || { cmd: [] };
      // 全局设置键值对
      const channel = getParam("channel");
      googletag.cmd.push(function () {
        if (channel) {
          googletag.pubads().setTargeting("afc_channel", channel);
        }

        if (gamConfig.topAnchorSlot) {
          topAnchorSlot = googletag.defineOutOfPageSlot(
            `${gamConfig.topAnchorSlot}`,
            googletag.enums.OutOfPageFormat.TOP_ANCHOR,
          );
          if (topAnchorSlot) {
            topAnchorSlot.addService(googletag.pubads());
          }
        }
        if (gamConfig.bottomAnchorSlot) {
          bottomAnchorSlot = googletag.defineOutOfPageSlot(
            `${gamConfig.bottomAnchorSlot}`,
            googletag.enums.OutOfPageFormat.BOTTOM_ANCHOR,
          );
          if (bottomAnchorSlot) {
            bottomAnchorSlot.addService(googletag.pubads());
          }
        }
        if (gamConfig.interstitialSlot) {
          interstitialSlot = googletag.defineOutOfPageSlot(
            `${gamConfig.interstitialSlot}`,
            googletag.enums.OutOfPageFormat.INTERSTITIAL,
          );
          if (interstitialSlot) {
            interstitialSlot.addService(googletag.pubads());
          }
        }
        // Enable SRA and services.
        googletag.pubads().enableSingleRequest();
        googletag.enableServices();
      });
    }
  }
};

const GAMAutoAdShow = () => {
  window.googletag = window.googletag || { cmd: [] };
  googletag.cmd.push(function () {
    // top anchor
    topAnchorSlot && googletag.display(topAnchorSlot);
    // bottom anchor
    bottomAnchorSlot && googletag.display(bottomAnchorSlot);
    // interstitial
    interstitialSlot && googletag.display(interstitialSlot);
  });
};

// GAM激励视频广告初始化 #goog_rewarded
export const GamRewardAdInit = (gamConfig, callback) => {
  if (typeof window !== "undefined") {
    if (gamConfig && !gamConfig.close && gamConfig.playRewardedVideoSlot) {
      window.googletag = window.googletag || { cmd: [] };
      let rewardedSlot;
      let rewardPayload;
      googletag.cmd.push(() => {
        if (gamConfig.playRewardedVideoSlot) {
          rewardedSlot = googletag.defineOutOfPageSlot(
            `${gamConfig.playRewardedVideoSlot}`,
            googletag.enums.OutOfPageFormat.REWARDED,
          );

          // Slot returns null if the page or device does not support rewarded ads.
          if (rewardedSlot) {
            rewardedSlot.addService(googletag.pubads());

            googletag.pubads().addEventListener("rewardedSlotReady", (event) => {
              let playBtn = document.getElementById("play-btn");
              if (playBtn) {
                playBtn.addEventListener("click", () => {
                  event.makeRewardedVisible();
                  trackEvent("GAM_RV_Pop", { Adslot: gamConfig.playRewardedVideoSlot });
                });
              }
            });

            googletag.pubads().addEventListener("slotRenderEnded", (event) => {
              const { positionName, path } = getPositionNameAndPath(event, gamConfig);
              if (positionName === "playRewardedVideoSlot") {
                if (event.isEmpty) {
                  // rewarded video展示失败
                  trackEvent("GAM_RV_Show_Fail", { Adslot: path });
                  // 点击play直接播放
                  let playBtn = document.getElementById("play-btn");
                  if (playBtn) {
                    playBtn.addEventListener("click", () => {
                      callback && callback();
                    });
                  }
                } else {
                  // rewarded video展示成功
                  trackEvent("GAM_RV_Show", { Adslot: path });
                }
              }
            });

            googletag.pubads().addEventListener("rewardedSlotClosed", (event) => {
              if (rewardedSlot) {
                googletag.destroySlots([rewardedSlot]);
              }
              callback && callback();
            });

            googletag.pubads().addEventListener("rewardedSlotGranted", (event) => {
              callback && callback();
              rewardPayload = event.payload;
            });

            googletag.enableServices();
            googletag.display(rewardedSlot);
          } else {
            console.log("rewardedSlot is null");
            callback && callback();
          }
        }
      });
    }
  }
};

// 游戏插屏广告初始化 #goog_game_inter
export const GameInterstitialAdInit = (gamConfig, callback) => {
  if (typeof window !== "undefined") {
    if (gamConfig && !gamConfig.close && gamConfig.playGameInterstitialSlot) {
      window.googletag = window.googletag || { cmd: [] };
      let gamingInterstitialSlot;
      googletag.cmd.push(() => {
        if (gamConfig.playGameInterstitialSlot) {
          gamingInterstitialSlot = googletag.defineOutOfPageSlot(
            `${gamConfig.playGameInterstitialSlot}`,
            googletag.enums.OutOfPageFormat.GAME_MANUAL_INTERSTITIAL,
          );

          // Slot returns null if the page or device does not support rewarded ads.
          if (gamingInterstitialSlot) {
            gamingInterstitialSlot.addService(googletag.pubads());

            googletag
              .pubads()
              .addEventListener("gameManualInterstitialSlotReady", (slotReadyEvent) => {
                if (gamingInterstitialSlot === slotReadyEvent.slot) {
                  let playBtn = document.getElementById("play-btn");
                  if (playBtn) {
                    playBtn.addEventListener("click", () => {
                      slotReadyEvent.makeGameManualInterstitialVisible();
                      trackEvent("GAM_MIV_Pop", { Adslot: gamConfig.playGameInterstitialSlot });
                    });
                  }
                }
              });

            googletag.pubads().addEventListener("slotRenderEnded", (event) => {
              const { positionName, path } = getPositionNameAndPath(event, gamConfig);
              if (positionName === "playGameInterstitialSlot") {
                if (event.isEmpty) {
                  // manual interstitial video展示失败
                  trackEvent("GAM_MIV_Show_Fail", { Adslot: path });
                  // 点击play直接播放
                  let playBtn = document.getElementById("play-btn");
                  if (playBtn) {
                    playBtn.addEventListener("click", () => {
                      callback && callback();
                    });
                  }
                } else {
                  // manual interstitial video展示成功
                  trackEvent("GAM_MIV_Show", { Adslot: path });
                }
              }
            });

            googletag.pubads().addEventListener("gameManualInterstitialSlotClosed", (event) => {
              if (gamingInterstitialSlot) {
                googletag.destroySlots([gamingInterstitialSlot]);
                trackEvent("GAM_MIV_Close", { Adslot: gamConfig.playGameInterstitialSlot });
              }
              callback && callback();
            });

            googletag.enableServices();
            googletag.display(gamingInterstitialSlot);
          } else {
            console.log("gamingInterstitialSlot is null");
            // 点击play直接播放
            let playBtn = document.getElementById("play-btn");
            if (playBtn) {
              playBtn.addEventListener("click", () => {
                callback && callback();
              });
            }
          }
        }
      });
    } else {
      // 没有对接游戏插屏广告, 点击play直接播放
      let playBtn = document.getElementById("play-btn");
      if (playBtn) {
        playBtn.addEventListener("click", () => {
          callback && callback();
        });
      }
    }
  }
};

// 广告点击处理
// 自动插屏是否展示
const isInterstitialShow = (iframe) => {
  let show = false;
  if (window.location.hash.indexOf("vignette") > -1) {
    let css = iframe.currentStyle || window.getComputedStyle(iframe);
    if (css.display !== "none" && iframe.clientWidth > 0 && iframe.clientHeight > 0) {
      show = true;
    }
  }
  return show;
};
// 激励视频是否展示
const isRewardedShow = (iframe) => {
  let show = false;
  if (window.location.hash.indexOf("goog_rewarded") > -1) {
    let css = iframe.currentStyle || window.getComputedStyle(iframe);
    if (css.display !== "none" && iframe.clientWidth > 0 && iframe.clientHeight > 0) {
      show = true;
    }
  }
  return show;
};
// 游戏手动插屏是否展示
const isGameManualInterstitialShow = (iframe) => {
  let show = false;
  if (window.location.hash.indexOf("goog_game_inter") > -1) {
    let css = iframe.currentStyle || window.getComputedStyle(iframe);
    if (css.display !== "none" && iframe.clientWidth > 0 && iframe.clientHeight > 0) {
      show = true;
    }
  }
  return show;
};
//当前页面是否因为点击iframe失去焦点
const isBlurTriggered = ref(false);

// 跟踪广告点击
const trackAdClick = (adConfig) => {
  const activeElement = document.activeElement;
  if (!activeElement) return;
  const src = activeElement.getAttribute("src");
  const id = activeElement.getAttribute("id");
  let isGam = false;

  if (id && id.indexOf(`/${adConfig.gam.id}/`) > -1) {
    isGam = true;
  }
  console.log("isgam", isGam);
  if (isGam) {
    let anchorContainer = activeElement.closest("[data-anchor-shown]");
    let interstitialContainer = activeElement.closest("[data-vignette-loaded]");
    if (interstitialContainer || id.indexOf("Interstitial") > -1) {
      console.log("gam intersititial");
      // GAM自动插屏广告点击。相关事件
      trackEvent(
        "GAM_Inter_Click_Auto",
        {
          Adslot: adConfig.gam.interstitialSlot,
        },
        {},
      );
      trackEvent(
        "GAM_AD_Click_Auto",
        {
          Adslot: adConfig.gam.interstitialSlot,
        },
        {},
      );
      trackEvent(
        "GAM_AD_Click_All",
        {
          Adslot: adConfig.gam.interstitialSlot,
        },
        {},
      );
    } else if (anchorContainer || id.indexOf("Anchor") > -1) {
      console.log("gam Anchor");
      // GAM自动锚定广告点击相关事件
      trackEvent(
        "GAM_Anc_Click_Auto",
        {
          Adslot: adConfig.gam.topAnchorSlot,
        },
        {},
      );
      trackEvent(
        "GAM_AD_Click_Auto",
        {
          Adslot: adConfig.gam.topAnchorSlot,
        },
        {},
      );
      trackEvent(
        "GAM_AD_Click_All",
        {
          Adslot: adConfig.gam.topAnchorSlot,
        },
        {},
      );
    } else if (id.indexOf(adConfig.gam.playRewardedVideoSlot) > -1) {
      console.log("gam reward");
      // reward video
      trackEvent(
        "GAM_RV_Click",
        {
          Adslot: adConfig.gam.playRewardedVideoSlot,
        },
        {},
      );
      trackEvent(
        "GAM_AD_Click_All",
        {
          Adslot: adConfig.gam.playRewardedVideoSlot,
        },
        {},
      );
    } else if (id.indexOf(adConfig.gam.playGameInterstitialSlot) > -1) {
      console.log("gam manual interstitial");
      // game manual interstitial
      trackEvent(
        "GAM_MIV_Click",
        {
          Adslot: adConfig.gam.playGameInterstitialSlot,
        },
        {},
      );
      trackEvent(
        "GAM_AD_Click_All",
        {
          Adslot: adConfig.gam.playGameInterstitialSlot,
        },
        {},
      );
    } else {
      // GAM手动广告点击，相关事件
      let gamAdSlot = activeElement.closest("[gam-slot]");
      // console.log('gamAdSlot', gamAdSlot);
      if (gamAdSlot) {
        const slot = gamAdSlot.getAttribute("gam-slot");
        console.log(`gam display ${slot}`);
        trackEvent(
          "GAM_AD_Click",
          {
            Adslot: slot,
          },
          {},
        );
        trackEvent(
          "GAM_AD_Click_All",
          {
            Adslot: slot,
          },
          {},
        );
      }
    }
  } else {
    // afc广告的点击
    // let anchorContainer = activeElement.closest("[data-anchor-shown]");
    // let interstitialContainer = activeElement.closest("[data-vignette-loaded]");
    let displayContainer = activeElement.closest("[data-ad-slot]");
    if (displayContainer) {
      console.log("afc display");
      // 手动广告点击
      const adSlot = displayContainer.getAttribute("data-ad-slot") || "null";
      // afc 手动广告点击
      trackEvent(
        "AD_Click",
        {
          Adslot: adSlot,
        },
        {},
      );
    }
  }
};

const windowMessage = () => {
  window._inter_close = false;
  // 监听广告iframe postMessage通知来判断广告关闭
  window.addEventListener("message", (event) => {
    // let adSenseDomain = 'https://googleads.g.doubleclick.net';
    // console.log('event', event.data);
    // gam interstitial close: {"msg_type":"i-dismiss","googMsgType":"sth"}

    if (event.data && typeof event.data === "string" && event.data.includes("adClosed")) {
      window._inter_close = true;
    }
  });
};

// 页面失去焦点
const windowBlur = () => {
  window.addEventListener("blur", () => {
    let ACTIVELEMENT = document.activeElement;
    if (
      "IFRAME" ===
      (null === ACTIVELEMENT || undefined === ACTIVELEMENT ? undefined : ACTIVELEMENT.nodeName)
    ) {
      isBlurTriggered.value = true;
      setTimeout(() => {
        isBlurTriggered.value = false;
        window.focus(); // 延时foucs，因为广告跳转前会获取activeElement，太早focus会导致跳转前activeElement是body
      }, 300);
    }
  });
};

// 页面展示隐藏
const windowVisible = (adConfig) => {
  window.addEventListener("visibilitychange", () => {
    if (document.visibilityState == "hidden" && isBlurTriggered.value) {
      trackAdClick(adConfig);
    } else if (document.visibilityState == "visible") {
      setTimeout(() => window.focus(), 0);
    }
  });
};

// 关闭页面之前
const windowBeforeUnload = (adConfig) => {
  window.addEventListener("beforeunload", () => {
    const ACTIVEELEMENT = document.activeElement;
    if (
      "IFRAME" ===
      (null === ACTIVEELEMENT || undefined === ACTIVEELEMENT ? undefined : ACTIVEELEMENT.nodeName)
    ) {
      if (isInterstitialShow(ACTIVEELEMENT) && window._inter_close) {
        // 页面内跳转，非广告点击
        console.log("interstitial close");
      } else {
        trackAdClick(adConfig);
      }
    }
  });
};

// 初始化客户端JS
export const headClientInit = (adConfig) => {
  // 审核模式不请求广告相关东西
  const config = getDomainConfig();
  if (config.isChecking) {
    return;
  }
  // 初始化GAM自动广告
  GAMAutoAdInit(adConfig.gam);
  // 监听GAM广告展示回调
  gamAutoAdShowTrack(adConfig.gam);

  windowMessage();
  windowBlur();
  windowVisible(adConfig);
  windowBeforeUnload(adConfig);
  // 最后执行GAM自动广告展示
  GAMAutoAdShow();
};

